<?php

namespace App\Services\client;

use App\Helpers\Check;
use App\Helpers\ResponseEnum;
use App\Models\admin\AdminUser;
use App\Models\admin\ApplicationRoles;
use App\Models\AdminApplication;
use App\Models\client\Platform;
use App\Models\client\PlatformUser;
use App\Services\BaseService;
use App\Services\common\DictionaryService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class PlatformService extends BaseService
{
    /**
     * 数据查询
     *
     * @return array
     */
    public static function getPageData($requestData)
    {
        [$perPage, $page, $orderBy, $orderDir] = [
            isset($requestData['perPage']) ? $requestData['perPage'] : 20,
            isset($requestData['page']) ? $requestData['page'] : 1,
            isset($requestData['orderBy']) ? $requestData['orderBy'] : 'id',
            isset($requestData['orderDir']) ? $requestData['orderDir'] : 'desc',
        ];
        $models = Platform::query();

        $list = $models->where(function ($query) use ($requestData) {
            if (isset($requestData['name'])) {
                $query->where('name', 'like', '%'.$requestData['name'].'%');
            }
            if (isset($requestData['category'])) {
                $query->where('category', $requestData['category']);
            }
        })->where('user_id', $requestData->user['id'])
            ->orderBy('id', 'desc')
            ->paginate();

        foreach ($list as $key => $value) {
            // 安装类别【1.微信小程序|2.微信公众号|3.PC|4.APP】
            $installation_category = '';
            if ($value['category'] == 1) {
                $category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius">微信小程序</button>';
            } elseif ($value['category'] == 2) {
                $category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius">微信公众号</button>';
            } elseif ($value['category'] == 3) {
                $category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius tag-item-warm">&nbsp;PC&nbsp;</button>';
            } elseif ($value['category'] == 4) {
                $category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius tag-item-warm" style="background-color: #f6ad55;">APP</button>';
            }
            $list[$key]->image = $value->logo == null ? BE_ADMIN.'/images/l_default.jpeg' : $value->logo;
            $list[$key]->title = $value['name'].'&nbsp;&nbsp;'.$category;
            $list[$key]->time = $value->is_lifespan == 1 ? '永久' : $value->start_time.'&nbsp;-&nbsp;'.$value->end_time;
        }

        return pearListAjaxReturn($list);
    }

    /**
     * 数据查询
     *
     * @return array
     */
    public static function getData($param)
    {
        $models = Platform::query();
        if (isset($requestData['status'])) {
            $models->whereIn('status', $requestData['status']);
        }

        $list = $models->with(['hasApplication'])->where(function ($query) use ($param) {
            if (isset($param['id'])) {
                $query->whereIn('id', $param['id']);
            }
            if (isset($param['name'])) {
                $query->where('name', 'like', '%'.$param['name'].'%');
            }
            if (isset($param['category'])) {
                $query->where('category', '%'.$param['category'].'%');
            }
            if (isset($param['user_id'])) {
                $query->where('user_id', $param['user_id']);
            }
        })->orderBy('id', 'desc')->get();
        foreach ($list as $key => $value) {
            $list[$key]->staff_count = PlatformUser::where('platform_id', $value->id)->where('role_id', '<>', 0)->count();
            $list[$key]->role_count = ApplicationRoles::where('platform_id', $value->id)->count();
            // 获取当前平台渠道
            $category = explode(',', $value->category);
            $dictionaryArr = [];
            foreach ($category as $k => $item) {
                $dictionaryArr[] = DictionaryService::getInfoByValue('installation_category', $item);
            }
            $list[$key]->dictionaryArr = $dictionaryArr;
        }

        return $list;
    }

    /**
     * 数据查询
     *
     * @return array
     */
    public static function getUserData($param)
    {
        $models = PlatformUser::query();

        $list = $models->where(function ($query) use ($param) {
            if (isset($param['app_id'])) {
                $query->where('app_id', $param['app_id']);
            }
            if (isset($param['userid'])) {
                $query->where('userid', $param['userid']);
            }
        })->get();

        return $list;
    }

    /**
     * 回收数据列表
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 11:44
     *
     * @Interface getRecyclePageData
     */
    public function getRecyclePageData()
    {
        $param = $this->request->input();
        $models = $this->model::onlyTrashed();

        if ($this->request->name) {
            $models->where('name', $this->request->name);
        }
        if ($this->request->installation_category) {
            $models->where('installation_category', $this->request->installation_category);
        }

        $list = $models->select('id', 'name', 'logo as image', 'remark', 'installation_category', 'module')->orderBy('id', 'desc')->paginate();

        foreach ($list as $key => $value) {
            // 安装类别【1.微信小程序|2.微信公众号|3.PC|4.APP】
            $installation_category = '';
            if ($value['installation_category'] == 1) {
                $installation_category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius" onclick="">微信小程序</button>';
            } elseif ($value['installation_category'] == 2) {
                $installation_category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius">微信公众号</button>';
            } elseif ($value['installation_category'] == 3) {
                $installation_category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius tag-item-warm">&nbsp;PC&nbsp;</button>';
            } elseif ($value['installation_category'] == 4) {
                $installation_category = '<button type="button" class="tag-item layui-btn layui-btn-primary layui-btn-sm layui-btn-radius tag-item-warm" style="background-color: #f6ad55;">APP</button>';
            }

            $list[$key]['title'] = $value['name'].'&nbsp;&nbsp;'.$installation_category;
            $list[$key]['time'] = '永久';
        }

        return pearListAjaxReturn($list);
    }

    /**
     * 总数
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 16:36
     *
     * @Interface count
     *
     * @return int
     */
    public function count($user_id)
    {
        $models = $this->model::onlyTrashed();

        return $models->where('user_id', $user_id)->count();
    }

    /**
     * 编辑
     *
     * @return \Illuminate\Http\JsonResponse
     * User: zhx
     * Date: 2023/6/30 14:28
     */
    public static function edit($id, $requestAll)
    {
        $models = Platform::query();

        $ret = $models->where('id', $id)->update($requestAll);

        return $ret;
    }

    /**
     * 添加
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-01
     *
     * @Time: 14:02
     *
     * @Interface create
     */
    public static function create($requestData)
    {
        $models = Platform::query();
        $ret = $models->create($requestData);

        return $ret;
    }

    /**
     * 删除
     *
     * @return \Illuminate\Http\JsonResponse
     * User: zhx
     * Date: 2023/6/30 14:30
     */
    public function destroy()
    {
        $param = $this->request->input();
        $models = $this->model::query();

        $ret = $models->where('id', $this->request->id)->delete();
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function info()
    {
        $param = $this->request->input();
        $models = $this->model::query();

        $info = $models->where(['id' => $this->request->route('id')])->first();
        if (! $info) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $info;
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getinfo($id)
    {
        $models = Platform::query();

        return $models->where(['id' => $id])->first();
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getinfoBynumber($number)
    {
        $models = Platform::query();

        return $models->where(['number' => $number])->first();
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getinfoByUidAndAppid($uid, $appid)
    {
        $models = Platform::query();

        return $models->where([
            'user_id' => $uid,
            'app_id' => $appid,
        ])->first();
    }

    /**
     * 恢复应用
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 12:00
     *
     * @Interface setDestroy
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDestroy()
    {
        $param = $this->request->input();
        $models = $this->model::onlyTrashed();

        //----------------------------------------------------
        // 操作
        //----------------------------------------------------
        $ret = $models->where('id', $this->request->route('id'))->restore();
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '保存失败');
        }

        return $this->success();
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfoByAdminUserId($admin_user_id, $app_id)
    {
        $models = $this->model::query();

        $info = $models->where('admin_user_id', $admin_user_id)->where('app_id', $app_id)->first();
        if (! $info) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }
        $info->data1 = json_decode($info->data1);
        $info->data2 = json_decode($info->data2);
        $info->data3 = json_decode($info->data3);
        $info->data4 = json_decode($info->data4);
        $info->data5 = json_decode($info->data5);
        $info->data6 = json_decode($info->data6);

        $appInfo = AdminApplication::where('id', $info->app_id)->first();

        // 保存session
        //        session([$appInfo->module => json_encode([
        //            'platform_id' => $info->id,
        //            'app_id' => $info->app_id,
        //        ])]);
        return $this->success($info);
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfoByInfo()
    {
        $param = $this->request->input();
        $models = $this->model::query();

        $info = $models->where(['id' => $param['id']])->first();
        if (! $info) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }
        $info->data1 = json_decode($info->data1);
        $info->data2 = json_decode($info->data2);
        $info->data3 = json_decode($info->data3);
        $info->data4 = json_decode($info->data4);
        $info->data5 = json_decode($info->data5);
        $info->data6 = json_decode($info->data6);

        $appInfo = AdminApplication::where('id', $info->app_id)->first();

        // 保存session
        //        session([$appInfo->module => json_encode([
        //            'platform_id' => $info->id,
        //            'app_id' => $info->app_id,
        //        ])]);
        return $this->success($info);
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfoById($id)
    {
        $models = $this->model::query();

        $info = $models->where(['id' => $id])->first();
        if ($info) {
            $info->data1 = json_decode($info->data1, true);
            $info->data2 = json_decode($info->data2, true);
            $info->data3 = json_decode($info->data3, true);
            $info->data4 = json_decode($info->data4, true);
            $info->data5 = json_decode($info->data5, true);
            $info->data6 = json_decode($info->data6, true);

            return $info;
        } else {
            return false;
        }
    }

    /**
     * 删除
     *
     * @return \Illuminate\Http\JsonResponse
     * User: zhx
     * Date: 2023/6/30 14:30
     */
    public function delete()
    {
        $param = $this->request->input();
        $models = $this->model::onlyTrashed();

        $ret = $models->where('id', $this->request->route('id'))->forceDelete();
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 平台菜单列表
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:17
     *
     * @Interface platformMenu
     *
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function platformMenu($platform_id)
    {
        $param = $this->request->input();
        $models = $this->model::query();

        // 获取平台信息
        $info = $models->where(['id' => $platform_id])->first();
        $info->data1 = json_decode($info->data1, true);
        $application = AdminApplication::whereIn('id', [$info->app_id])->orderBy('id', 'desc')->get();

        $data_app = [];
        foreach ($application as $value) {
            $data_app[] = [
                'id' => (string) Str::uuid(),
                'title' => $value->name,
                'icon' => 'layui-icon layui-icon-console',
                'type' => 1,
                'openType' => '_iframe',
                'href' => "/platform/{$value->id}/app_info",
            ];
        }

        $data = [
            [
                'id' => (string) Str::uuid(),
                'title' => '应用模块',
                'type' => 0,
                'icon' => 'layui-icon layui-icon-console',
                'children' => $data_app,
            ],
            [
                'id' => (string) Str::uuid(),
                'title' => '基础管理',
                'type' => 0,
                'icon' => 'layui-icon layui-icon-set',
                'children' => [
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '平台配置',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=0",
                    ],
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '开发配置',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=1",
                    ],
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '上传配置',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=4",
                    ],
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '短信配置',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=5",
                    ],
                    //                    [
                    //                        "id" => (string)Str::uuid(),
                    //                        "title" => '邮箱配置',
                    //                        "icon" => "layui-icon layui-icon-console",
                    //                        "type" => 1,
                    //                        "openType" => "_iframe",
                    //                        "href" => "/platform/{$info->id}/edit?type=6"
                    //                    ],
                ],
            ],
            [
                'id' => (string) Str::uuid(),
                'title' => '平台管理',
                'type' => 0,
                'icon' => 'layui-icon layui-icon-slider',
                'children' => [
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '角色管理',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=role",
                    ],
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '员工管理',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=staff",
                    ],
                ],
            ],
            [
                'id' => (string) Str::uuid(),
                'title' => '支付管理',
                'type' => 0,
                'icon' => 'layui-icon layui-icon-slider',
                'children' => [
                    [
                        'id' => (string) Str::uuid(),
                        'title' => '支付配置',
                        'icon' => 'layui-icon layui-icon-console',
                        'type' => 1,
                        'openType' => '_iframe',
                        'href' => "/platform/{$info->id}/edit?type=paysetting",
                    ],
                ],
            ],
        ];

        // 平台类别【1.微信小程序|2.微信公众号|3.PC|4.APP】）
        return Response::json($data);
    }

    /**
     * 邮箱配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface emailEdit
     */
    public function emailEdit()
    {
        $param = $this->request->input();
        $models = $this->model::query();
        // 邮箱配置
        $validator = Validator::validate($param, [
            'id' => 'required',
            'MAIL_DRIVER' => 'required',
            'MAIL_HOST' => 'required',
            'MAIL_PORT' => 'required',
            'MAIL_USERNAME' => 'required',
            'MAIL_PASSWORD' => 'required',
            'MAIL_ENCRYPTION' => 'required',
            'MAIL_FROM_ADDRESS' => 'required',
            'MAIL_FROM_NAME' => 'required',
        ], [
            'id.required' => 'id不能为空',
            'MAIL_DRIVER.required' => '驱动名称 不能为空',
            'MAIL_HOST.required' => '服务地址 不能为空',
            'MAIL_PORT.required' => '服务端口 不能为空',
            'MAIL_USERNAME.required' => '发件邮箱 不能为空',
            'MAIL_PASSWORD.required' => '发件邮箱授权码 不能为空',
            'MAIL_ENCRYPTION.required' => '加密/协议 不能为空',
            'MAIL_FROM_ADDRESS.required' => '来源地址 不能为空',
            'MAIL_FROM_NAME.required' => '来源名称 不能为空',
        ]);
        $data['data6'] = json_encode($validator);
        $ret = $models->where('id', $validator['id'])->update($data);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 短信配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface smsEdit
     */
    public function smsEdit()
    {
        $param = $this->request->input();
        $models = $this->model::query();
        // sms 配置
        $validator = Validator::validate($param, [
            'id' => 'required',
            'sms_service_id' => 'required',
            'ACCESS_KEY_ID' => 'required',
            'ACCESS_KEY_SECRET' => 'required',
            'SIGN_NAME' => 'required',
        ], [
            'id.required' => 'id不能为空',
            'sms_service_id.required' => '服务商 不能为空',
            'ACCESS_KEY_ID.required' => '访问KEY 不能为空',
            'ACCESS_KEY_SECRET.required' => '访问密钥 不能为空',
            'SIGN_NAME.required' => '签名名称 不能为空',
        ]);
        if ($validator['sms_service_id'] == 1) {
            $validator['sms_service_name'] = '阿里云';
        }
        $data['data5'] = json_encode([
            'sms_service' => [
                'id' => $validator['sms_service_id'],
                'name' => $validator['sms_service_name'],
            ],
            'ACCESS_KEY_ID' => $validator['ACCESS_KEY_ID'],
            'ACCESS_KEY_SECRET' => $validator['ACCESS_KEY_SECRET'],
            'SIGN_NAME' => $validator['SIGN_NAME'],
        ]);
        $ret = $models->where('id', $validator['id'])->update($data);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * OSS配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface ossEdit
     */
    public function ossEdit()
    {
        $param = $this->request->input();
        $models = $this->model::query();
        // OSS配置
        $validator = Validator::validate($param, [
            'id' => 'required',
            'storage_disks_id' => 'required',
            'AccessKeyId' => '',
            'AccessKeySecret' => '',
            'bucket' => '',
            'OSS_ENDPOINT' => '',
        ], [
            'id.required' => 'id不能为空',
            'storage_disks_id.required' => '存储位置 不能为空',
        ]);

        if ($validator['storage_disks_id'] == 1) {
            $validator['storage_disks_name'] = '本地';
        } elseif ($validator['storage_disks_id'] == 2) {
            $validator['storage_disks_name'] = '阿里云';
        }

        $data['data4'] = json_encode([
            'storage_disks' => [
                'id' => $validator['storage_disks_id'],
                'name' => $validator['storage_disks_name'],
            ],
            'AccessKeyId' => $validator['AccessKeyId'],
            'AccessKeySecret' => $validator['AccessKeySecret'],
            'bucket' => $validator['bucket'],
            'OSS_ENDPOINT' => $validator['OSS_ENDPOINT'],
        ]);
        $ret = $models->where('id', $validator['id'])->update($data);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 开发配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface developEdit
     */
    public function developEdit()
    {
        $param = $this->request->input();
        $models = $this->model::query();
        // 开发配置
        $validator = Validator::validate($param, [
            'id' => 'required',
            'AppId' => 'required',
            'AppSecret' => 'required',
        ], [
            'id.required' => 'id不能为空',
            'AppId.required' => 'AppId 不能为空',
            'AppSecret.required' => 'AppSecret 不能为空',
        ]);

        $data['data1'] = json_encode([
            'AppId' => $validator['AppId'],
            'AppSecret' => $validator['AppSecret'],
        ]);
        $ret = $models->where('id', $validator['id'])->update($data);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 详细配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface infoEdit
     */
    public function infoEdit()
    {
        $param = $this->request->input();
        $models = $this->model::query();
        // 基础信息配置
        $validator = Validator::validate($param, [
            'id' => 'required',
            'logo' => '',
            'qr_code' => '',
            'name' => 'required',
            'remark' => 'required',
        ]);

        //----------------------------------------------------
        // 验证和上传头像
        //----------------------------------------------------
        $data = [
            'id' => $validator['id'],
            'logo' => $validator['logo'],
            'qr_code' => $validator['qr_code'],
            'name' => $validator['name'],
            'remark' => $validator['remark'],
        ];
        $ret = $models->where('id', $validator['id'])->update($data);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 支付配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface developEdit
     */
    public function paysettingEdit()
    {
        $param = $this->request->input();
        $models = $this->model::query();
        // 开发配置
        $validator = Validator::validate($param, [
            'id' => 'required',
            'is_pay' => 'required',
            'mch_id' => '',
            'key_v3' => '',
            'pay_cert' => '',
            'pay_key' => '',
        ], [
            'id.required' => 'id不能为空',
            'is_pay.required' => '是否开启支付不能为空',
        ]);

        $data['is_pay'] = isset($validator['is_pay']) ? true : false;
        // 微信支付配置
        $data['data_wx_pay'] = json_encode([
            'mch_id' => isset($validator['mch_id']) ?? '',
            'key_v3' => isset($validator['key_v3']) ?? '',
            'pay_cert' => isset($validator['pay_cert']) ?? '',
            'pay_key' => isset($validator['pay_key']) ?? '',
        ]);
        //        # 支付宝支付配置
        //        $data['data_wx_pay'] = json_encode([
        //            'mch_id' => $validator['mch_id'],
        //            'key_v3' => $validator['key_v3'],
        //            'pay_cert' => $validator['pay_cert'],
        //            'pay_key' => $validator['pay_key'],
        //        ]);
        $ret = $models->where('id', $validator['id'])->update($data);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 角色详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleInfo($id)
    {
        $models = ApplicationRoles::query();

        $info = $models->where(['id' => $id])->first();
        if (! $info) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $info;
    }

    /**
     * 角色配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface developEdit
     */
    public function roleCreate()
    {
        $param = $this->request->input();
        $models = ApplicationRoles::query();
        // 开发配置
        $validator = Validator::validate($param, [
            'platform_id' => 'required',
            'name' => 'required',
            'permissions' => '',
        ], [
            'platform_id.required' => '平台id不能为空',
            'name.required' => '角色名称不能为空',
        ]);
        $param['auth_ids'] = implode(',', $param['permissions']);

        $ret = $models->create($param);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 更新角色配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface developEdit
     */
    public function roleEdit()
    {
        $param = $this->request->input();
        $models = ApplicationRoles::query();
        // 开发配置
        $validator = Validator::validate($param, [
            'platform_id' => 'required',
            'id' => 'required',
            'name' => 'required',
            'permissions' => '',
        ], [
            'platform_id.required' => '平台id不能为空',
            'name.required' => '角色名称不能为空',
        ]);
        $validator['auth_ids'] = isset($validator['permissions']) ? implode(',', $validator['permissions']) : '';
        unset($validator['permissions']);

        $ret = $models->where('id', $param['id'])->update($validator);
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 删除角色
     *
     * @return \Illuminate\Http\JsonResponse
     * User: zhx
     * Date: 2023/6/30 14:30
     */
    public function roleDestroy($id)
    {
        $models = ApplicationRoles::query();

        $ret = $models->where('id', $id)->delete();
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }

    /**
     * 员工详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-03
     *
     * @Time: 16:14
     *
     * @Interface info
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function staffInfo($id)
    {
        $models = AdminUser::query();

        $info = $models->with(['hasPlatformUsers'])->where('is_admin', 1)->where('is_staff', 1)->where(['id' => $id])->first();
        if (! $info) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $info;
    }

    /**
     * 员工配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface developEdit
     */
    public function staffCreate($requestAll)
    {
        DB::beginTransaction();
        try {
            $models = AdminUser::query();
            //----------------------------------------------------
            // 验证
            //----------------------------------------------------
            $validator = Validator::validate($requestAll, [
                'avatar' => 'required',
                'name' => 'required',
                'username' => 'required',
                'password' => 'required',
                'req_password' => 'required',
                'platform_id' => 'required',
                'app_id' => 'required',
                'role_id' => 'required',
            ]);

            // 验证确认密码
            if ($validator['req_password'] != $validator['password']) {
                return $this->fail(ResponseEnum::HTTP_ERROR, null, '确认密码错误');
            }
            $checkRes = Check::passwordDetection($validator['password']);
            if ($checkRes['code'] == false) {
                return $this->fail(ResponseEnum::HTTP_ERROR, null, $checkRes['msg']);
            }
            //----------------------------------------------------
            // 判断用户名是否重复
            //----------------------------------------------------
            $count = $models->where('username', $validator['username'])->count();
            if ($count != 0) {
                return $this->fail(ResponseEnum::HTTP_ERROR, null, '用户名已存在');
            }

            // 保存员工账号
            $data = [
                'name' => $validator['name'],
                'username' => $validator['username'],
                'password' => password_hash($validator['password'], PASSWORD_BCRYPT),
                'avatar' => $validator['avatar'],
                'is_admin' => 1,
                'is_staff' => 1,
                'state' => 1,
            ];
            $ret = $models->create($data);
            // 创建和平台关联关系
            $p_user = PlatformUser::create([
                'platform_id' => $validator['platform_id'],
                'app_id' => $validator['app_id'],
                'admin_user_id' => $ret->id,
                'role_id' => $validator['role_id'],
                'name' => $validator['name'],
                'status' => 1,
            ]);
            if (! $ret && ! $p_user) {
                DB::rollBack();

                return $this->fail(ResponseEnum::HTTP_ERROR, null, '保存失败');
            }
            // 保存
            DB::commit();

            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->fail(ResponseEnum::HTTP_ERROR, null, '保存失败');
        }
    }

    /**
     * 更新员工配置
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-06
     *
     * @Time: 17:30
     *
     * @Interface developEdit
     */
    public function staffEdit($requestAll)
    {
        DB::beginTransaction();
        try {
            $models = AdminUser::query();
            //----------------------------------------------------
            // 验证
            //----------------------------------------------------
            $validator = Validator::validate($requestAll, [
                'avatar' => 'required',
                'name' => 'required',
                'role_id' => 'required',
                'id' => 'required',
            ]);

            // 保存员工账号
            $data = [
                'name' => $validator['name'],
                'avatar' => $validator['avatar'],
            ];
            $ret = $models->where('id', $validator['id'])->update($data);

            // 创建和平台关联关系
            $p_user = PlatformUser::where('admin_user_id', $validator['id'])->update([
                'role_id' => $validator['role_id'],
                'name' => $validator['name'],
            ]);
            if (! $ret && ! $p_user) {
                DB::rollBack();

                return $this->fail(ResponseEnum::HTTP_ERROR, null, '更新失败');
            }
            // 保存
            DB::commit();

            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->fail(ResponseEnum::HTTP_ERROR, null, '更新失败');
        }
    }

    /**
     * 删除员工
     *
     * @return \Illuminate\Http\JsonResponse
     * User: zhx
     * Date: 2023/6/30 14:30
     */
    public function staffDestroy($id)
    {
        $models = ApplicationRoles::query();

        $ret = $models->where('id', $id)->delete();
        if (! $ret) {
            return $this->fail(ResponseEnum::HTTP_ERROR, null, '操作失败');
        }

        return $this->success();
    }
}
